const ipUtil = require("../../utils/hostUtil")
const requestUtil = require("../../utils/requestUtil")
Page({

    /**
     * 页面的初始数据
     */
    data: {
        goodsList: [],
        checkList: [],
        edit: false,
        selectAll: false,
        cartId: "",
        totalCount: 0,
        totalPrice: "0.00",
        templateEnable: false,
        skuList: {
            data: [],
            checkedid: "",
            sku: ""
        }
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad: function (options) {

    },
	
	//领券
	to_coupon:function(){
		wx.navigateTo({
			url:'/pages/coupon/coupon'
		})
	},

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady: function () {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow: function () {
        // 每当页面显示时更新购物车列表
        this.loadPage();
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide: function () {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload: function () {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh: function () {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom: function () {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage: function () {

    },
    /**
     * 减少购物车中商品数量
     * @param index 当前选中的购物车下标
     * @param id 购物车id
     */
    decreaseCount: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var id = e.currentTarget.dataset.id;
        var data = this.data.goodsList
        var count = data[index].account--;
        if (count-1>= 0) {
            wx.request({
                url: `${ipUtil.host}${requestUtil.desCartCount}`,
                data: {cartId: id},
                method: "POST",
                header: requestUtil.header,
                success(res) {
					console.log(res)
                    if (res.data.code == 0) {
                        data[index].account = --count;
                        that.setData({
                            goodsList: data
                        })
                    }
                }
            })
        } else {
            wx.showToast({
                title: "该商品不能再减少了哟~",
                icon: "none",
                duration: 2000
            })
        }
		this.totalCountAndPrice();
    },
    /**
     * 增加购物车中商品数量
     * @param index 当前所在的下标
     * @param id 购物车id
     */
    addCount: function (e) {
        var that = this;
        var index = e.currentTarget.dataset.index;
        var id = e.currentTarget.dataset.id;
        var data = this.data.goodsList
        var count = data[index].account++;
		console.log(count)
        if (count + 1 <= 999) {
            wx.request({
                url: `${ipUtil.host}${requestUtil.addCartCount}`,
                data: {cartId: id},
                method: "POST",
                header: requestUtil.header,
                success(res) {
					console.log(res)
                    if (res.data.code == 0) {
                        data[index].account = ++count;
						console.log(count)
                        that.setData({
                            goodsList: data
                        })
                    } else {
                        wx.showToast({
                            title: res.data.msg,
                            icon: "none",
                            duration: 2000
                        })
                    }
                }
            })
        } else {
            wx.showToast({
                title: "该商品不能购买更多哦~",
                icon: "none",
                duration: 2000
            })
        }
		this.totalCountAndPrice();
    },
    /**
     * 显示选择规格页面
     * @param skuId 当前选中的购物车的sku
     * @param fruitId 需要查询的商品id
     */
    changeSpecification: function (e) {
        var that = this;
        var skuId = e.currentTarget.dataset.skuid;
        var fruitId = e.currentTarget.dataset.fruitid;
        var cartId = e.currentTarget.dataset.cartid;
        this.setData({
            cartId: cartId,
            templateEnable: true,
        })
        // 显示选择商品规格页面
        wx.request({
            url: `${ipUtil.host}${requestUtil.skuList}`,
            data: {fruitId: fruitId},
            method: "POST",
            header: requestUtil.header,
            success(res) {
                var sku;
                if (res.data.rows) {
                    res.data.rows.forEach(item => {
                        if (item.skuId == skuId) {
                            sku = item;
                        }
                    })
                    that.setData({
                        skuList: {
                            data: res.data.rows,
                            checkedid: skuId,
                            sku: sku
                        }
                    })
                }
            }
        })
        // 修改this.data({})以刷新页面显示
    },
    /**
     * 全选或者反选所有商品
     * @param e 当前选中状态
     */
    selectAll: function (e) {
        var arr = this.data.checkList;
        var checked = this.data.selectAll;
        for (var a = 0; a < arr.length; a++) {
            arr[a] = !checked;
        }
        this.setData({
            selectAll: !checked,
            checkList: arr
        })
        this.totalCountAndPrice();
    },
    /**
     * 管理商品菜单 后期可能会加 收藏商品
     */
    chengeEdit: function () {
        // 重置选中状态
        var checkList = this.data.checkList;
        checkList.map((item) => {
            return false
        })
        this.setData({
            checkList: checkList,
            edit: !this.data.edit,
            selectAll: false
        })

    },
    /**
     * 删除购物车商品,
     */
    deleteGoods: function () {
        var checkList = this.data.checkList;
        var goodsList = this.data.goodsList;
        var deleteArr = [];
        for (let i = 0; i < goodsList.length; i++) {
            if (checkList[i]) {
                deleteArr.push(goodsList[i].cartId);
            }
        }
        var that = this;
        wx.showModal({
            title: '删除商品',
            content: `确定要删除${deleteArr.length}个商品吗？`,
            showCancel: true,//是否显示取消按钮
            cancelText: "否",//默认是“取消”
            cancelColor: 'grey',//取消文字的颜色
            confirmText: "是",//默认是“确定”
            confirmColor: 'red',//确定文字的颜色
            success: function (res) {
                if (res.cancel) {
                    //点击取消,默认隐藏弹框
                } else {
                    that.confirmDelete(deleteArr)
                }
            },
        })
    },
    /**
     * 确认删除购物车中商品
     * @param deleteArr
     */
    confirmDelete: function (deleteArr) {
        var that = this;
        wx.request({
            url: `${ipUtil.host}${requestUtil.deleteCarts}`,
            data: {
                cartIds: deleteArr
            },
            method: "POST",
            header: requestUtil.header,
            success(res) {
                console.log(res)
                if (res.data.code == 0) {
                    that.loadPage();
                    wx.showToast({
                        title: "删除成功",
                        icon: "success",
                        duration: 1500
                    })
                }
            }
        })
    },
    /**
     *  生成订单
     */
    submitOrders: function () {
        // 选中的商品的索引
        var checkList = this.data.checkList;
        var goodsList = this.data.goodsList;
        var submitarr = [];
        goodsList.forEach((item, index) => {
            if (checkList[index]) {
                submitarr.push(item.cartId)
            }
        })
        wx.request({
            url: `${ipUtil.host}${requestUtil.generateOrder}`,
            data: {
                cartIds: submitarr
            },
            method: "POST",
            header: requestUtil.header,
            success(res) {
                if (res.data.code==0) {
                    wx.navigateTo({
                        url: `/pages/order/suborder?id=${res.data.data.orderId}`
                    })
                } else {
                    wx.showToast({
                        title: "生成订单失败",
                        icon: "none",
                        duration: 2000
                    })
                }
            }
        })
    },
    /**
     *  统计选中的商品数量以及价钱
     */
    totalCountAndPrice: function () {
        var checkList = this.data.checkList;
        var goodsList = this.data.goodsList;
		console.log(goodsList)
        var totalCount = 0;
        var totalPrice = 0.00;
        goodsList.forEach((item, index) => {
            if (checkList[index]) {
				console.log(item.account)
                totalCount++;
                totalPrice += (item.sku.userIPrice * item.account)
				console.log(totalPrice)
            }
        })
        this.setData({
            totalCount: totalCount,
            totalPrice: totalPrice.toFixed(2)
        })
		console.log(totalPrice)
    },
    /**
     * 改变商品选中的数组
     * @param index 当前点击的radio的下标
     */
    chengeCheckList: function (e) {
        var index = e.currentTarget.dataset.index
        var checkList = this.data.checkList;
        checkList[index] = !checkList[index];
        this.setData({
            checkList: checkList,
			selectAll:false
        })
        this.totalCountAndPrice();
    },
    /**
     * 关闭商品选择规格面板
     */
    closeTemplateAndOprate: function () {
        var that=this;
        this.setData({
            templateEnable: false
        })
        wx.request({
            url: `${ipUtil.host}${requestUtil.car_update_specification}`,
            data: {cartId:this.data.cartId,skuId:this.data.skuList.sku.skuId},
            method: "POST",
            header: requestUtil.header,
            success(res) {
                // 修改成功 修改this.data中的数据
                if(res.data.code==0){
                    that.loadPage();
                }
            }
        })
    },
    closeTemplate: function () {
        this.setData({
            templateEnable: false
        })
    },
    /**
     * 设置选中的skuid
     * @param cartId 购物车id
     * @param id skuId
     */
    changeChecked: function (e) {
        var id = e.currentTarget.dataset.skuid;
        var data = this.data.skuList.data;
        var sku;
        data.forEach(item => {
            if (item.skuId == id) {
                sku = item;
            }
        })
        this.setData({
            skuList: {
                data: this.data.skuList.data,
                checkedid: id,
                sku: sku
            }
        })
    },
    /**
     * 提交规格修改
     */
    submitChange: function () {
        wx.request({
            url: `${ipUtil.host}${requestUtil.car_update_specification}`,
            method: "POST",
            data: {
                cartId: this.data.cartId,
                skuId: this.data.skuList.sku
            },
            header: requestUtil.header,
            success(res) {
                if (res.code > 0) {
                    // 重新显示购物车列表
                    this.loadPage();
                }
            }
        })
    },
	to_detail:function(e){
		let id = e.currentTarget.dataset.fruitid
		wx.navigateTo({
		    url: `/pages/detail/detail?id=${id}`
		})
	},
    /**
     * 请求购物车列表数据
     */
    loadPage: function () {
        var that = this;
        wx.request({
            url: `${ipUtil.host}${requestUtil.cart_list}`,
            data: {token: wx.getStorageSync("token")},
            method: "POST",
            header: requestUtil.header,
            success(res) {
                var arr = [];
                for (var a = 0; a < res.data.data.length; a++) {
                    arr.push(false)
                }
                if (res.data.data) {
                    that.setData({
                        goodsList: res.data.data,
                        checkList: arr,
                        selectAll:false,
                        totalCount: 0,
                        totalPrice: 0.00
                    })
                }
            }
        })
    }
})